# Copyright 2007 pyPayPal Dev Team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 only
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

import paypal_exceptions, constants, objects
from urllib import urlencode, unquote, FancyURLopener

class PayPal:
    """ Base class for interacting with PayPal. """

    def __init__(self, user, passwd, signature=None, certificate=None, key=None,
                 development=False, gateway=None, url=None, version=constants.API_VERSION):
        self.api_gateway = gateway
        self.api_url = url
        self.version = version
        self.signature = signature
        self.certificate = certificate
        self.key = key
        self.development = development
        # Do we do this?
        #self.__last_response = None
        self.account_data = {
        'USER': user,
        'PWD': passwd,
        'VERSION': self.version,
        }
        if self.signature: self.account_data['SIGNATURE'] = signature
        self.signature_uri = urlencode(self.account_data)

class PayPalNVP(PayPal):
    """ Interface to PayPal's NVP API. """

    def set_gateway(self):
        """ Set desired gateway information. """
        if not (self.certificate and self.key):
            if self.development:
                self.api_gateway = 'https://api-3t.sandbox.paypal.com/nvp'
                self.api_url = 'https://www.sandbox.paypal.com/webscr'
            else:
                self.api_gateway = 'https://api-3t.paypal.com/nvp'
                self.api_url = 'https://www.paypal.com/webscr'
        else:
             # FIXME: Add in certificate based auth
             pass
    def post_request(self, action):
        """ POST Request to PayPal. """
        
        # Check to make sure everything is valid
        action.is_valid()
            
        # If we get here, then the action is valid.  Send it to Paypal
        data_uri = "%s&%s" % (self.signature_uri, action.get_uri())
        full_url = "%s?%s" % (self.api_gateway, data_uri)
        if self.development: 
            print full_url
        opener = FancyURLopener()
        #try:
        request = opener.open(self.api_gateway, data_uri)
        #except:
            #raise PayPalError, 'Failed request.'
        #    pass
        if self.development: print "Request information: %s\n" % request.info()
        response_handler = objects.NVP_Response_Handler()
        
        try:
            response_handler.parse_response(request)
            action.get_response_values(response_handler)
        except paypal_exceptions.ResponseWarning:
            print "TX was successful, but had warnings\n"
        except:
            print "TX failed\n"
            
        if self.development: 
            for item in response_handler.tokens.keys():
                print "%s: %s" % (item, unquote(response_handler.tokens[item]))
        

#class PayPalSOAP(PayPal):
#     """ Interface to PayPal's SOAP API. """
#
#     def set_gateway(self):
#        """ Set desired gateway information. """
#        if self.development:
            # FIXME: Test API version and make correct selection(s)
            # FIXME: Update for the SOAP gateway and URL
            #self.api_gateway = 'https://api-3t.sandbox.paypal.com/nvp'
            #self.api_url = 'https://www.sandbox.paypal.com/webscr'
#            pass
      
